import { defineStore } from 'pinia';
import { UserState } from "../types";
import { pinia } from '../index'

const useUserStore = defineStore("user-info", {
    state: () => {
        return {
            userId: 0,
            token: "",
            userName: "",
            userNickname: "",
            residentId: "",
            userAge: 0,
            userType: 0,
            telephone: "",
        }
    },
    actions: {
        saveUser(userInfo: UserState) {
            return new Promise<UserState>((resolve) => {
                this.userId = userInfo.userId
                this.userName = userInfo.userName
                this.token = userInfo.token
                this.userNickname = userInfo.userNickname
                this.userType = userInfo.userType
                this.residentId = userInfo.residentId
                this.userAge = userInfo.userAge
                this.telephone = userInfo.telephone
                resolve(userInfo)
            })
        },
        isTokenExpire() {
            return !this.token;
        },
        logout() {
            return new Promise<void>((resolve) => {
                this.$reset()
                localStorage.clear();
                sessionStorage.clear();
                resolve();
            })
        }
    }
})
export default useUserStore

export function useUserStoreContext() {
    return useUserStore(pinia)
  }
  